<template>
    <vp-dialog ref="editDialogRef" :span=1>
        <template #title>{{$t('systemDataGroup.item.user')}}</template>
        <el-transfer
            v-loading="loading"
            filterable
            :filter-method="filterMethod"
            style="width:100%;text-align:center"
            v-model="rightData"
            :props="{
                key:'id',
                label: 'name'
            }"
            :titles="[$t('item.unselected'), $t('item.selected')]"
            :data="data"
        >
        </el-transfer>
        <template #footer>
            <el-button :loading="saveLoading"  type='primary' @click="handleSave">{{$t("btn.confirm")}}</el-button>
        </template>
    </vp-dialog>
</template>
<script lang="ts">
import { defineComponent, reactive, ref, toRefs } from 'vue'
import request from '/@/utils/request';

export default defineComponent({
    name:'editDataGroupUser',
    emits:["formSubmited"],
    components: {},
    setup(props,context) {
        const state = reactive({
            loading: false,
            saveLoading: false,
            data:[],
            rightData:[] as any[],
            id: "",
            pageType: 1, //页面类型，1功能角色 2机型角色
		});
        const editDialogRef = ref();

        const init = ()=>{
            state.data = [];
            state.rightData=[];
        }
        const handleOpen = (pageType:number, id: string)=>{
            init();
            state.id = id;
            state.pageType = pageType;
            editDialogRef.value.handleOpen();
            state.loading = true;
            request.get(`/system/dataGroup/user/${id}`).then((res)=>{
                state.data = res?.data||[];
                let selectedData = [] as any[];
                state.data.forEach((value: any)=>{
                    if(value.flag === 1){
                        selectedData.push(value.id);
                    }
                });
                state.rightData = selectedData;
                state.loading = false;
            })
        }

        const handleSave = ()=>{
             if(state.loading){
                return;
            }
            state.saveLoading = true;
            request.post("/system/dataGroup/user/"+state.id, state.rightData).then(()=>{
                context.emit("formSubmited");
                editDialogRef.value.handleClose();
            }).catch(()=>{
            }).finally(()=>{
                state.saveLoading = false;
            })
        }

        const filterMethod = (query, item) => {
            return item.name.toLowerCase().includes(query.toLowerCase())
        }

        return {
            ...toRefs(state),
            editDialogRef,
            handleOpen,
            handleSave,
            filterMethod,
        }
    },
})
</script>
<style lang="scss" scoped>
:deep(.el-transfer-panel__body .el-input) {
    height: auto;
}
</style>